﻿using System;
using System.Data.Linq;
using System.Linq;

namespace TempEmployees.DAL
{
    partial class DepartmentsInfo
    {
        public DepartmentsInfo(int departmentId, int semesterId, int students = 0) : this()
        {
            DepartmentID = departmentId;
            SemesterID = semesterId;
            RegisteredStudents = students;
        }

        public string DepartmentName { get { return Department.Name; } }

        #region validations
        
        private bool uniqeKeyChanged = false;

        partial void OnValidate(System.Data.Linq.ChangeAction action)
        {
            if (!uniqeKeyChanged ||
                (action != ChangeAction.Insert && action != ChangeAction.Update))
                return;
            TempEmpDatabaseDataContext db = new TempEmpDatabaseDataContext();
            var query = db.DepartmentsInfos.Where<DepartmentsInfo>(
                (di) => di.DepartmentID == this.DepartmentID && di.SemesterID == this.SemesterID);
            if (query.Count() > 1) throw new InvalidOperationException("Can't have two rows with both DepartmentID and SemesterID equal");
        }

        partial void OnDepartmentIDChanged()
        {
            uniqeKeyChanged = true;
        }

        partial void OnSemesterIDChanged()
        {
            uniqeKeyChanged = true;
        }
        
        #endregion
    }
}
